﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.BosCheck.Dto;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TZ.PlugIn.FileSrv
{
    [Description("采购订单下载签署文档到附件管理")]
    [Kingdee.BOS.Util.HotUpdate]

    public class PurOrderDownloadFile : AbstractBillPlugIn
    {
        private string FormId = "PUR_PurchaseOrder";

        public override void BarItemClick(Kingdee.BOS.Core.DynamicForm.PlugIn.Args.BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            if (e.BarItemKey.EqualsIgnoreCase("tbDownFile"))
            {
                var BillNo = this.View.Model.GetValue("FBillNo").ToString();
                var sql = "";
                var DocumentId = "";
                if (!this.View.Model.GetValue("FDocumentId").IsNullOrEmpty())
                    DocumentId = this.View.Model.GetValue("FDocumentId").ToString();
                if (DocumentId == "")
                {
                    this.View.ShowMessage("没有上传签署文件");
                    return;
                }
                var FContractId = "";
                if (!this.View.Model.GetValue("FContractId").IsNullOrEmpty())
                    FContractId = this.View.Model.GetValue("FContractId").ToString();
                if (FContractId == "")
                {
                    this.View.ShowMessage("没有创建电子签约单");
                    return;
                }
                var FisDownload = Convert.ToBoolean(this.View.Model.GetValue("FisDownload").ToString());
                if (FisDownload)//已下载合同附件，不能重复下载
                {
                    //this.View.ShowMessage("已下载，不允许重复下载");
                    //return;
                    //如果已经下载过，先删除掉
                    DelAchment(BillNo);
                }

                FormId = this.View.BusinessInfo.GetForm().Id;

                try
                {

                    var ErrMsg = "";
                    var FilePath = Guid.NewGuid().ToString() + ".PDF";
                    var FileName = BillNo + ".PDF";//定义文件名：单据编号为文件名
                    FilePath = PathUtils.GetPhysicalPath("TempfilePath", FilePath);//获取金蝶临时目录
                    if (!Directory.Exists(FilePath))//目录不存在，则创建目录
                        Directory.CreateDirectory(FilePath);
                    FilePath = FilePath + @"\" + FileName;//文件名为单据编号
                    var isPost = true;
                    Common.GetParams(this.Context);
                    var Url = string.Format(Common.DownloadUrl, DocumentId);
                    Common.GetFile(Url, Common.AppToken, Common.AppSecret, FilePath, ref isPost, ref ErrMsg);
                    if (!isPost)
                    {
                        this.View.ShowErrMessage(ErrMsg);
                        return;
                    }
                    else
                    {
                        var InterId = this.View.Model.DataObject["Id"].ToString();
                        //检查附件名是否已上传过
                        sql = string.Format("SELECT top 1 FID FROM T_BAS_ATTACHMENT WHERE FBILLTYPE = '{0}' AND FINTERID = '{1}' and FATTACHMENTNAME = '{2}'", FormId, InterId, FileName);
                        var dyExists = DBUtils.ExecuteDynamicObject(this.Context, sql);
                        //if (dyExists.Count > 0)
                        //{
                        //    this.View.ShowErrMessage("附件【" + FileName + "】已经存在，不能重复上传");
                        //    return;
                        //}

                        var isUpload = true;//上传成功标识
                        var blockSize = 1024 * 1024; // 分块大小：1M
                        var FileId = string.Empty;
                        using (var fsRead = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            if (fsRead.Length <= 0)
                            {
                                this.View.ShowErrMessage("上传附件，单据编号【" + BillNo + "】，附件名【" + FileName + "】为空文件");
                                isUpload = false;
                                return;
                            }
                            while (true)
                            {
                                var content = new byte[blockSize];
                                int size = fsRead.Read(content, 0, content.Length);
                                if (size == 0)
                                {
                                    isUpload = false;
                                    break;
                                }
                                var IsLast = (size != blockSize);
                                var uploadBytes = new byte[size];
                                Array.Copy(content, uploadBytes, size);
                                var SendByte = Convert.ToBase64String(uploadBytes);

                                var JsonData = Common.CreateUploadJson(FileName, FormId, IsLast, InterId, BillNo, FileId, SendByte);
                                var ReturnMsg = WebApiServiceCall.AttachmentUpload(this.Context, JsonData.ToString());
                                var Result = JObject.Parse(JsonUtil.Serialize(ReturnMsg));
                                if (!Convert.ToBoolean(Result["Result"]["ResponseStatus"]["IsSuccess"].ToString()))
                                {
                                    //上传失败
                                    var ErrorMsg = Common.GetErrMsg(Result);
                                    this.View.ShowErrMessage("上传附件，单据编号【" + BillNo + "】，附件名【" + FileName + "】失败：" + ErrorMsg);
                                    isUpload = false;
                                    break;
                                }
                                else
                                {
                                    //上传成功，获取文件id，分多次上传时，首次上传之后必填
                                    FileId = Result["Result"]["FileId"].ToString();
                                    // 获取客户端临时目录
                                    //string clientTempPath = Path.GetTempPath();
                                    //string clientFilePath = Path.Combine(clientTempPath, FileName);
                                    //AttachmentDownLoad(FileId, clientTempPath, clientFilePath);

                                    if (IsLast)
                                        break;
                                }
                            }
                        }
                        if (isUpload)
                        {
                            sql = string.Format("update T_PUR_POORDER set FisDownload = 1 where FBILLNO = '{0}'", BillNo);
                            DBUtils.Execute(this.Context, sql);
                            this.View.ShowMessage("下载附件成功！");

                            // 将文件发送到客户端并打开
                            // 打开文件下载界面(下载界面关闭后，临时文件会被删除)

                            // 生成文件的下载地址(Url: http:\\localhost\K3Cloud\...\xxx.xlsx)
                            var FilePath2 = PathUtils.GetPhysicalPath("TempfilePath");//获取金蝶临时目录
                            string clientFilePath = Path.Combine(FilePath2, FileName);
                            AttachmentDownLoad(FileId, FilePath2, clientFilePath, FileName);

                            //var fileUrl = PathUtils.GetServerPath("TempfilePath", FileName);
                            //var appUrl = PathUtils.GetAppCallingPath();

                            //var showParameter = new DynamicFormShowParameter();

                            //showParameter.FormId = "BOS_FileDownLoad";

                            //showParameter.OpenStyle.ShowType = ShowType.Modal;

                            //showParameter.CustomParams.Add("url", fileUrl);

                            //this.View.ShowForm(showParameter);

                            // 写上机操作日志
                            //var logs = new List<LogObject>();
                            //var log = new LogObject();
                            //log.pkValue = "";
                            //log.Description = $"下载合同到客户端:+{fileUrl},{appUrl}";
                            //log.OperateName = "下载合同到客户端";
                            //log.ObjectTypeId = "";
                            //log.SubSystemId = "";
                            //log.Environment = OperatingEnvironment.BizOperate;
                            //logs.Add(log);
                            //LogServiceHelper.BatchWriteLog(this.Context, logs);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.View.ShowErrMessage("下载文件异常：" + ex.Message);
                }
            }
        }

        private void DelAchment(string billNo)
        {
            //撤回时删除已经上传的附件
            var InterId = this.View.Model.DataObject["Id"].ToString();
            var FileName = billNo + ".PDF";//定义文件名：单据编号为文件名
            string sql = string.Format("SELECT  FID FROM T_BAS_ATTACHMENT WHERE FBILLTYPE = '{0}' AND FINTERID = '{1}' and FATTACHMENTNAME = '{2}'", "PUR_PurchaseOrder", InterId, FileName);
            var dyExists = DBUtils.ExecuteDynamicObject(this.Context, sql);
            var delAttchmentIds = new List<string>();
            if (dyExists.Count > 0)
            {
                foreach (var dye in dyExists)
                {
                    delAttchmentIds.Add(dye["FID"].ToString());//构建需要删除的FID集合 
                }
            }

            if (delAttchmentIds.Count > 0)
            {
                FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, "BOS_Attachment");

                DynamicObjectType wlType = meta.BusinessInfo.GetDynamicObjectType();

                BusinessDataServiceHelper.Delete(this.Context, delAttchmentIds.ToArray(), meta.BusinessInfo.GetDynamicObjectType());
            }
        }

        /// <summary>
        /// 把附件下载到本地
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="clientTempPath"></param>
        /// <param name="clientFilePath"></param>
        private void AttachmentDownLoad(string fileId, string clientTempPath, string clientFilePath, string fileName)
        {
            try
            {
                // 构造下载请求数据
                JObject downloadRequest = new JObject
        {
            { "FileId", fileId },
            { "StartIndex", 0 }
        };

                // 调用WebApiServiceCall.AttachmentDownLoad方法下载文件
                var downloadResult = WebApiServiceCall.AttachmentDownLoad(this.Context, downloadRequest.ToString());

                // 检查返回结果是否为字符串（可能包含错误信息）
                if (downloadResult is string stringResult)
                {
                    // 尝试解析字符串为JSON
                    try
                    {
                        JObject dResult = JObject.Parse(stringResult);
                        ProcessDownloadResult(dResult, clientFilePath, fileName);
                    }
                    catch (JsonReaderException)
                    {
                        // 如果不是JSON，可能是错误消息
                        this.View.ShowMessage($"下载失败: {stringResult}");
                    }
                }
                else
                {
                    // 如果已经是对象，直接序列化再解析
                    string jsonResponse = JsonUtil.Serialize(downloadResult);
                    JObject dResult = JObject.Parse(jsonResponse);
                    ProcessDownloadResult(dResult, clientFilePath, fileName);
                }
            }
            catch (Exception ex)
            {
                this.View.ShowMessage($"下载过程中发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理下载结果
        /// </summary>
        /// <param name="dResult">解析后的JSON结果</param>
        /// <param name="clientFilePath">文件保存路径</param>
        private void ProcessDownloadResult(JObject dResult, string clientFilePath, string fileName)
        {
            if (dResult != null && dResult["Result"] != null)
            {
                var result = dResult["Result"];
                if (result["ResponseStatus"]?["IsSuccess"]?.ToObject<bool>() == true)
                {
                    // 获取文件内容并保存到本地
                    string fileContent = result["FilePart"].ToString();
                    File.WriteAllBytes(clientFilePath, Convert.FromBase64String(fileContent));
                    Console.WriteLine("文件下载成功，保存路径：" + clientFilePath);

                    // 生成文件的下载地址(Url: http:\\localhost\K3Cloud\...\xxx.xlsx)

                    var fileUrl = PathUtils.GetServerPath("TempfilePath", fileName);
                    var appUrl = PathUtils.GetAppCallingPath();

                    var showParameter = new DynamicFormShowParameter();

                    showParameter.FormId = "BOS_FileDownLoad";

                    showParameter.OpenStyle.ShowType = ShowType.Modal;

                    showParameter.CustomParams.Add("url", fileUrl);

                    this.View.ShowForm(showParameter);
                }
                else
                {
                    string errorMessage = result["ResponseStatus"]?["Errors"]?.ToString() ?? "未知错误";
                    this.View.ShowMessage($"文件下载失败: {errorMessage}");
                }
            }
            else
            {
                this.View.ShowMessage("下载结果为空或格式不正确，请检查请求参数。");
            }
        }
    }
}
